package juc.topic;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 两个线程交替打印出a1b2c3.....z26
 */
public class AlternatePrintingNumberLetter02 {
    private static final ReentrantLock lock = new ReentrantLock();

    private static final Condition numCondition = lock.newCondition();
    private static final Condition letterCondition = lock.newCondition();

    //是否由数字线程执行标记
    private static boolean printNumber = true;


    public static void main(String[] args) {

        new Thread(() -> {
            for (int i = 1; i <= 26; i++) {
                lock.lock();
                try {
                    while (!printNumber) {
                        numCondition.await();
                    }
                    System.out.print(i);
                    printNumber = false;
                    //唤醒letterCondition
                    letterCondition.signal();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }, "数字线程").start();


        new Thread(() -> {
            for (char i = 'a'; i < 'z'; i++) {
                lock.lock();
                    try {
                        while (printNumber) {
                            try {
                                letterCondition.await();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        System.out.print(i);
                        printNumber = true;
                        numCondition.signal();
                    }catch (Exception e){
                        throw new RuntimeException(e);
                    }finally{
                        lock.unlock();
                    }
                }
        }, "字母线程").start();
    }
}
